﻿#include"XHuffmanTree.h"
#include"XAlgorithm.h"
//设置哈夫曼编码
static void setCode(XHfmNode* root,std::vector<char>*code)
{
	XHfmNode* curentNode = root;//当前节点
	XHfmNode* parent = curentNode->parent();//当前的父节点
	char ch = 0;//哈夫曼编码
	//循环找父
	while (parent !=NULL)
	{
		//当前是其父节点的左孩子
		if (curentNode == parent->leftChild())
		{
			ch = 0;
		}
		else
		{
			ch = 1;
		}
		code->push_back(ch);
		curentNode = parent;
		parent= curentNode->parent();
	}
	//将编码逆序
	std::reverse(code->begin(), code->end());
}
//获取哈夫曼编码数组以及对应的节点
static void getCode(XHfmNode* root)
{
	XHfmNodeData data = root->data();//根据二叉树节点获取其数据的指针
	if (data.code != NULL)
	{
		//printf("data:%d count:%d\n", LPdata->ch, LPdata->count);
		setCode(root, data.code);
		//XVector_iterator_for_each(LPdata->code, printCode, NULL);
		//printf("\n");
	}
}
void XHuffmanTree::setCode()
{
	if (ISNULL(root, "当前还未建立树"))
		return;
	auto  nodeList = root->traversing(XBTree::Inorder);
	for (auto& node:nodeList)
	{
		getCode(node);
	}
}

